/**
 * Created by XianTao on 2015/8/6
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.lego.wechat.base.encrypt;

import com.mysql.jdbc.StringUtils;
import org.apache.commons.codec.binary.Base64;
import org.lego.util.DateTimeUtil;
import org.lego.util.HashUtil;
import org.lego.util.PKCS7Util;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

public class WxMsgCryptKit {
    private static Charset CHARSET = Charset.forName("utf-8");
    Base64 base64 = new Base64();
    private byte[] aesKey;
    private String token;
    private String corpId;

    private WxMsgCryptKit(String token, String encodingAesKey, String corpId) throws WxAesException {
        if (encodingAesKey == null || encodingAesKey.length() != 43) {
            throw new WxAesException(WxAesException.IllegalAesKey);
        }
        this.token = token;
        this.corpId = corpId;
        this.aesKey = Base64.decodeBase64(encodingAesKey + "=");
    }

    /**
     * 创建对象，等同于构造函数
     *
     * @param token          公众平台上，开发者设置的token
     * @param encodingAesKey 公众平台上，开发者设置的EncodingAESKey
     * @param corpId         企业的corpId
     * @throws WxAesException
     */
    public static WxMsgCryptKit create(String token, String encodingAesKey, String corpId) throws WxAesException {
        return new WxMsgCryptKit(token, encodingAesKey, corpId);
    }

    /**
     * 将字节数组转化为十六进制字符串
     *
     * @param byteArray 字节数组
     * @return 十六进制字符串
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (byte aByteArray : byteArray) {
            strDigest += byteToHexStr(aByteArray);
        }
        return strDigest;
    }

    /**
     * 将字节转化为十六进制字符串
     *
     * @param b 一个byte
     * @return 十六进制字符串
     */
    private static String byteToHexStr(byte b) {
        char[] digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tmpArr = new char[2];
        tmpArr[0] = digit[(b >>> 4) & 0X0F];
        tmpArr[1] = digit[b & 0X0F];
        return new String(tmpArr);
    }

    /**
     * 验证企业号的回调url
     *
     * @param msgSignature 签名串
     * @param timestamp    时间戳
     * @param nonce        随机数
     * @param echostr      加密的随机字符串
     * @return 解密后的echostr
     * @throws WxAesException
     */
    public String verifyUrl(String msgSignature, String timestamp, String nonce, String echostr) throws WxAesException {
        String[] array = new String[]{token, timestamp, nonce, echostr};
        Arrays.sort(array);
        StringBuilder sb = new StringBuilder();
        for (String s : array) {
            sb.append(s);
        }
        String signature = HashUtil.sha1(sb.toString());
        if (!signature.equals(msgSignature)) {
            throw new WxAesException(WxAesException.ValidateSignatureError);
        }
        return decrypt(echostr);
    }

    /**
     * 验证订阅号或服务号的回调url
     *
     * @param signature 签名串
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   加密的随机字符串
     * @return 解密后的echostr
     * @throws WxAesException
     */
    public String verifyUrlNormal(String signature, String timestamp, String nonce, String echostr) throws WxAesException {
        String[] arr = {token, timestamp, nonce};
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();
        for (String anArr : arr) {
            content.append(anArr);
        }

        MessageDigest md;
        String tmpStr = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(content.toString().getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        if (tmpStr == null || !tmpStr.equals(signature.toUpperCase())) {
            throw new WxAesException(WxAesException.ValidateSignatureError);
        }
        return echostr;
    }

    /**
     * 检验消息的真实性，并且获取解密后的明文.
     * <ol>
     * <li>利用收到的密文生成安全签名，进行签名验证</li>
     * <li>若验证通过，则提取xml中的加密消息</li>
     * <li>对消息进行解密</li>
     * </ol>
     *
     * @param msgSignature 签名串，对应URL参数的msg_signature
     * @param timestamp    时间戳，对应URL参数的timestamp
     * @param nonce        随机串，对应URL参数的nonce
     * @param postData     密文，对应POST请求的数据
     * @return 解密后的原文
     * @throws WxAesException 执行失败，请查看该异常的错误码和具体的错误信息
     */
    public String decryptMsg(String msgSignature, String timestamp, String nonce, String postData) throws WxAesException {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            StringReader sr = new StringReader(postData);
            InputSource is = new InputSource(sr);
            Document document = db.parse(is);

            Element root = document.getDocumentElement();
            NodeList nodeList = root.getElementsByTagName("Encrypt");
            String encrypt = nodeList.item(0).getTextContent();

            String[] array = new String[]{token, timestamp, nonce, encrypt};
            Arrays.sort(array);
            StringBuilder sb = new StringBuilder();
            for (String s : array) {
                sb.append(s);
            }
            String signature = HashUtil.sha1(sb.toString());
            if (!signature.equals(msgSignature)) {
                throw new WxAesException(WxAesException.ValidateSignatureError);
            }
            return decrypt(encrypt);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将公众平台回复用户的消息加密打包
     * <ol>
     * <li>对要发送的消息进行AES-CBC加密</li>
     * <li>生成安全签名</li>
     * <li>将消息密文和安全签名打包成xml格式</li>
     * </ol>
     *
     * @param replyMsg  公众平台待回复用户的消息，xml格式的字符串
     * @param timestamp 时间戳，可以自己生成，也可以用URL参数的timestamp
     * @param nonce     随机串，可以自己生成，也可以用URL参数的nonce
     * @return 加密后的可以直接回复用户的密文，包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串
     * @throws WxAesException 执行失败，请查看该异常的错误码和具体的错误信息
     */
    public String encryptMsg(String replyMsg, String timestamp, String nonce) throws WxAesException {
        // 加密
        String encrypt = encrypt(getRandomStr(), replyMsg);

        // 生成安全签名
        if (StringUtils.isNullOrEmpty(timestamp)) {
            timestamp = Long.toString(DateTimeUtil.getCurrentTimeMillis());
        }

        String[] array = new String[]{token, timestamp, nonce, encrypt};
        Arrays.sort(array);
        StringBuilder sb = new StringBuilder();
        for (String s : array) {
            sb.append(s);
        }
        String signature = HashUtil.sha1(sb.toString());

        // 生成发送的xml
        return generate(encrypt, signature, timestamp, nonce);
    }

    /**
     * 对密文进行解密
     *
     * @param text 要解密的密文
     * @return 解密后的明文
     * @throws WxAesException
     */
    private String decrypt(String text) throws WxAesException {
        byte[] original;
        try {
            // 设置解密模式为AES的CBC模式
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES");
            IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
            cipher.init(Cipher.DECRYPT_MODE, key_spec, iv);

            // 使用BASE64对密文进行解码
            byte[] encrypted = Base64.decodeBase64(text);

            // 解密
            original = cipher.doFinal(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
            throw new WxAesException(WxAesException.DecryptAESError);
        }

        String xmlContent, from_corpid;
        try {
            // 去除补位字符
            byte[] bytes = PKCS7Util.decode(original);

            // 分离16位随机字符串,网络字节序和corpId
            byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);

            int xmlLength = recoverNetworkBytesOrder(networkOrder);

            xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET);
            from_corpid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length),
                    CHARSET);
        } catch (Exception e) {
            e.printStackTrace();
            throw new WxAesException(WxAesException.IllegalBuffer);
        }

        // corpId不相同的情况
        if (!from_corpid.equals(corpId)) {
            throw new WxAesException(WxAesException.ValidateCorpidError);
        }
        return xmlContent;

    }

    /**
     * 对明文进行加密
     *
     * @param text 需要加密的明文
     * @return 加密后base64编码的字符串
     * @throws WxAesException aes加密失败
     */
    String encrypt(String randomStr, String text) throws WxAesException {
        ByteGroup byteCollector = new ByteGroup();
        byte[] randomStrBytes = randomStr.getBytes(CHARSET);
        byte[] textBytes = text.getBytes(CHARSET);
        byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length);
        byte[] corpidBytes = corpId.getBytes(CHARSET);

        // randomStr + networkBytesOrder + text + corpid
        byteCollector.addBytes(randomStrBytes);
        byteCollector.addBytes(networkBytesOrder);
        byteCollector.addBytes(textBytes);
        byteCollector.addBytes(corpidBytes);

        // ... + pad: 使用自定义的填充方式对明文进行补位填充
        byte[] padBytes = PKCS7Util.encode(byteCollector.size());
        byteCollector.addBytes(padBytes);

        // 获得最终的字节流, 未加密
        byte[] unencrypted = byteCollector.toBytes();

        try {
            // 设置加密模式为AES的CBC模式
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
            IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);

            // 加密
            byte[] encrypted = cipher.doFinal(unencrypted);

            // 使用BASE64对加密后的字符串进行编码
            return base64.encodeToString(encrypted);
        } catch (Exception e) {
            throw new WxAesException(WxAesException.EncryptAESError);
        }
    }

    // 生成4个字节的网络字节序
    byte[] getNetworkBytesOrder(int sourceNumber) {
        byte[] orderBytes = new byte[4];
        orderBytes[3] = (byte) (sourceNumber & 0xFF);
        orderBytes[2] = (byte) (sourceNumber >> 8 & 0xFF);
        orderBytes[1] = (byte) (sourceNumber >> 16 & 0xFF);
        orderBytes[0] = (byte) (sourceNumber >> 24 & 0xFF);
        return orderBytes;
    }

    // 还原4个字节的网络字节序
    private int recoverNetworkBytesOrder(byte[] orderBytes) {
        int sourceNumber = 0;
        for (int i = 0; i < 4; i++) {
            sourceNumber <<= 8;
            sourceNumber |= orderBytes[i] & 0xff;
        }
        return sourceNumber;
    }

    // 随机生成16位字符串
    String getRandomStr() {
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 16; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 生成xml消息
     *
     * @param encrypt   加密后的消息密文
     * @param signature 安全签名
     * @param timestamp 时间戳
     * @param nonce     随机字符串
     * @return 生成的xml字符串
     */
    private String generate(String encrypt, String signature, String timestamp, String nonce) {

        String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n"
                + "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n"
                + "<TimeStamp>%3$s</TimeStamp>\n" + "<Nonce><![CDATA[%4$s]]></Nonce>\n" + "</xml>";
        return String.format(format, encrypt, signature, timestamp, nonce);

    }

    private class ByteGroup {
        ArrayList<Byte> byteContainer = new ArrayList<Byte>();

        public byte[] toBytes() {
            byte[] bytes = new byte[byteContainer.size()];
            for (int i = 0; i < byteContainer.size(); i++) {
                bytes[i] = byteContainer.get(i);
            }
            return bytes;
        }

        public ByteGroup addBytes(byte[] bytes) {
            for (byte b : bytes) {
                byteContainer.add(b);
            }
            return this;
        }

        public int size() {
            return byteContainer.size();
        }
    }
}
